<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="72px">
      <el-form-item label="节目标题" prop="chapterTitle">
        <el-input
          v-model="courseTitle"
          :disabled=true
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节标题" prop="chapterTitle">
        <el-input
          v-model="queryParams.chapterTitle"
          placeholder="请输入章节标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择章节状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['course:coursetype:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="coursechapterList"
      row-key="chapterId"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="章节标题" prop="chapterTitle" class-name="small-padding fixed-width" />
      <el-table-column
        label="是否父章节"
        align="center"
        prop="isParentChapter" 
        :formatter="isParentChapterFormat"
      />
      <!-- <el-table-column
        label="章节资源类型"
        align="center"
        prop="chapterSourceType"
        :formatter="chapterSourceTypeFormat"
      /> -->
      <!-- <el-table-column label="章节时长" align="center" width="100" prop="chapterLength" /> -->
      <el-table-column label="章节状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:maintaincourse:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:menu:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:maintaincourse:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改培训章节管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-row>
          <el-form-item label="上级章节" prop="courseId" style="display:none">
            <el-input v-model="form.courseId" placeholder="请输入章节标题" />
          </el-form-item>
          <el-col :span="12" style="height:58px">
            <el-form-item label="上级章节" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="chapterOptions"
                :show-count="true"
                placeholder="选择上级章节"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="章节标题" prop="chapterTitle">
              <el-input v-model="form.chapterTitle" placeholder="请输入章节标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是父章节" prop="isParentChapter">
              <el-radio-group v-model="form.isParentChapter">
                <el-radio
                  v-for="dict in isParentChapterOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.isParentChapter!='1'">
            <el-form-item label="章节时长" prop="chapterLength">
              <el-input v-model="form.chapterLength" placeholder="请输入章节时长" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-show="form.isParentChapter!='1'">
            <el-form-item label="资源路径" prop="chapterSourceUrl">
              <el-upload
                ref="upload"
                :limit="1"
                class="upload-demo"
                :http-request="uploadVideo"
                action="aa"
                :file-list="fileList"
                drag
                :before-upload="beforeUpload"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
                <el-progress v-if="startUpload" :percentage="uploadProgress"></el-progress>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-show="form.isParentChapter=='0'">
            <el-form-item label="章节试读" prop="hasFreeLimit">
              <el-select v-model="form.hasFreeLimit" placeholder="请选择章节试读额度" clearable>
                <el-option
                  v-for="dict in hasFreeLimitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.isParentChapter!='1'">
            <el-form-item label="试读时长" prop="chapterFreeLimit">
              <el-input
                v-model="form.chapterFreeLimit"
                placeholder="请输入章节试读时长"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.isParentChapter!='1'">
            <el-form-item label="资源类型" prop="chapterSourceType">
              <el-select v-model="form.chapterSourceType" placeholder="请选择章节资源类型">
                <el-option
                  v-for="dict in chapterSourceTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="章节描述" prop="chapterDes">
              <el-input v-model="form.chapterDes" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style >
.el-upload-dragger {
  width: 240px;
  height: 140px;
}
.el-upload-dragger .el-icon-upload {
  margin: 14px 0 16px;
}
.el-upload-dragger .el-upload__text {
  font-size: 12px;
}
</style>
<script>

import { listCourse, getCourse, delCourse, addCourse, updateCourse, exportCourse } from "@/api/wechat/course";
import { listChapter, getChapter, delChapter,treeselect, addChapter, updateChapter, exportChapter } from "@/api/wechat/chapter";

import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import TcVod from 'vod-js-sdk-v6'

import { getVodSignature } from '@/api/upload.js'

export default {
  components: { Treeselect, IconSelect },
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      chapterOptions: [],
      // 遮罩层
      loading: true,
      startUpload:false,
      uploadProgress:0,
      fileList:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      courseId: undefined,
      // 非多个禁用
      multiple: true,
      courseTitle:"",
      // 总条数
      total: 0,
      // 培训章节管理表格数据
      coursechapterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否父章节(父章节只显示标题) 0否 1是字典
      isParentChapterOptions: [],
      // 章节资源类型 0视频 1音频 2链接 3文字字典
      chapterSourceTypeOptions: [],
      // 付费类型 0免费 1付费字典
      payTypeOptions: [],
      // 付费类型 0原价 1限时特价 2会员价字典
      discountTypeOptions: [],
      hasFreeLimitOptions: [],
      // 是否有考试字典
      hasExamOptions: [],
      // 章节状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        courseId: undefined,
        pageNum: 1,
        pageSize: 10,
        courseId: undefined,
        parentId: undefined,
        chapterTitle: undefined,
        viewNum: undefined,
        likeNum: undefined,
        isParentChapter: undefined,
        chapterSourceType: undefined,
        chapterSourceUrl: undefined,
        chapterThumbUrl: undefined,
        chapterDes: undefined,
        chapterValidStartTime: undefined,
        chapterValidEndTime: undefined,
        payType: undefined,
        payValue: undefined,
        discountType: undefined,
        discountValue: undefined,
        payMemeberValue: undefined,
        chapterLength: undefined,
        hasExam: undefined,
        status: undefined,
        orderNum: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级章节不能为空", trigger: "blur" }
        ],
        chapterTitle: [
          { required: true, message: "章节标题不能为空", trigger: "blur" }
        ]
        // hasFreeLimit: [
        //   { r, message: "章节试读不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.courseId = this.$route.params && this.$route.params.courseId;
    if (this.courseId)
      getCourse(this.courseId).then(response => {
        this.courseTitle = response.data.courseTitle;
      });
    this.queryParams.courseId = this.courseId;
    this.getList();
    this.getDicts("is_parent_chapter").then(response => {
      this.isParentChapterOptions = response.data;
    });
    this.getDicts("chapter_source_type").then(response => {
      this.chapterSourceTypeOptions = response.data;
    });
    this.getDicts("free_limit_type").then(response => {
      this.hasFreeLimitOptions = response.data;
    });
    this.getDicts("pay_type").then(response => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("discount_type").then(response => {
      this.discountTypeOptions = response.data;
    });
    this.getDicts("has_exam").then(response => {
      this.hasExamOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // handleChange(file, fileList) {
    //     // this.fileList = [];
    // },
    async uploadVideo(event){
        this.startUpload=true
        var that=this;
        // const { data } = await getVodSignature()
        const getSignature = async function() {
          const { data } = await getVodSignature()
          return data;
        }
        console.log(event)
        // console.log(data)
        this.mediaFile = event.file
        this.fileSize = event.file.size
        console.log(this.mediaFile)
        console.log( this.fileSize)
        const tcVod = new TcVod({
          getSignature: getSignature,
        })
        const uploader = tcVod.upload({ videoFile: this.mediaFile })
        // 监听上传完成
        　// 视频上传完成时
        uploader.on('media_upload', function(info) {
          console.log('视频上传完成')
          console.log(info)
          uploaderInfo.isVideoUploadSuccess = true;
          if(uploaderInfo.isCoverUploadSuccess){
          }
        })
        // 视频上传进度
        uploader.on('media_progress', function(info) {
          console.log('视频上传中',(info.percent*100).toFixed(0))
          that.uploadProgress=parsenInt((info.percent*100).toFixed(2))
          // that.$refs.upload.onProgress({percent:percent})
        })
        // 封面上传完成时
        uploader.on('cover_upload', function(info) {
          console.log('封面上传完成')
          uploaderInfo.isCoverUploadSuccess = true;
          if(uploaderInfo.isVideoUploadSuccess){
          }
        })
        // 封面上传进度
        uploader.on('cover_progress', function(info) {
          console.log('封面上传中',(info.percent*100).toFixed(0))
        })
 
        var uploaderInfo = {
          videoInfo: uploader.videoInfo,
          coverInfo: uploader.coverInfo,
          isVideoUploadSuccess: false,
          isVideoUploadCancel: false,
          isCoverUploadSuccess: false,
          progress: 0,
          coverProgress: 0,
          fileId: "",
          videoUrl: "",
          coverUrl: "",
          cancel: function() {
            uploaderInfo.isVideoUploadCancel = true;
            uploader.cancel();
          }
        }
        this.uploaderInfo = uploaderInfo
        uploader.done().then(function (doneResult) {
          uploaderInfo.fileId = doneResult.fileId;
          var vurl = doneResult.video.url
          var vurls = vurl.split('/')
          var _vurls = vurl.split('.')
          that.form.chapterSourceUrl = doneResult.video.url
          that.startUpload=false
          // that.fileList=[]
          // var file={}
          // file.name="source1";
          // file.url=doneResult.video.url;
          // that.fileList.push(file)
        })

    },
    beforeUpload(){

    },
    beforeAvatarUpload(file) {
      return true;
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      treeselect(this.queryParams).then(response => {
        this.chapterOptions = [];
        const chapterType = { id: 0, label: "培训课程", children: [] };
        chapterType.children = response.data;
        this.chapterOptions.push(chapterType);
      });
    },
    /** 查询培训章节管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.courseId = this.courseId;
      listChapter(this.queryParams).then(response => {
        this.coursechapterList = response.data;
        this.loading = false;
      });
    },
    // 是否父章节(父章节只显示标题) 0否 1是字典翻译
    isParentChapterFormat(row, column) {
      return this.selectDictLabel(
        this.isParentChapterOptions,
        row.isParentChapter
      );
    },
    // 章节资源类型 0视频 1音频 2链接 3文字字典翻译
    chapterSourceTypeFormat(row, column) {
      return this.selectDictLabel(
        this.chapterSourceTypeOptions,
        row.chapterSourceType
      );
    },
    // 付费类型 0免费 1付费字典翻译
    payTypeFormat(row, column) {
      return this.selectDictLabel(this.payTypeOptions, row.payType);
    },

    // 章节试读额度 0无试读 1部分试读 2全部试读字典翻译
    hasFreeLimitFormat(row, column) {
      return this.selectDictLabel(this.hasFreeLimitOptions, row.hasFreeLimit);
    },
    // 付费类型 0原价 1限时特价 2会员价字典翻译
    discountTypeFormat(row, column) {
      return this.selectDictLabel(this.discountTypeOptions, row.discountType);
    },
    // 是否有考试字典翻译
    hasExamFormat(row, column) {
      return this.selectDictLabel(this.hasExamOptions, row.hasExam);
    },
    // 章节状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.upload) this.$refs.upload.clearFiles();
      this.form = {
        courseId: this.courseId,
        chapterId: undefined,
        courseId: undefined,
        parentId: undefined,
        chapterTitle: undefined,
        viewNum: undefined,
        likeNum: undefined,
        isParentChapter: "1",
        chapterSourceType: undefined,
        chapterSourceUrl: undefined,
        hasFreeLimit: undefined,
        chapterFreeLimit: undefined,
        chapterThumbUrl: undefined,
        chapterDes: undefined,
        chapterValidStartTime: undefined,
        chapterValidEndTime: undefined,
        payType: undefined,
        payValue: undefined,
        discountType: undefined,
        discountValue: undefined,
        payMemeberValue: undefined,
        chapterLength: undefined,
        hasExam: undefined,
        status: "0",
        orderNum: 1,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chapterId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.chapterId;
      }
      this.open = true;
      this.title = "添加培训章节管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const chapterId = row.chapterId || this.ids;
      getChapter(chapterId).then(response => {
        this.fileList=[]
        this.form = response.data;
        if(response.data.chapterSourceUrl){
          var file={}
          file.name="source1";
          file.url=response.data.chapterSourceUrl;
          this.fileList.push(file)
        }
        this.open = true;
        this.title = "修改培训章节管理";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.chapterId != undefined) {
            this.form.courseId = this.courseId;
            updateChapter(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            this.form.courseId = this.courseId;
            addChapter(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chapterIds = row.chapterId || this.ids;
      this.$confirm(
        '是否确认删除培训章节管理编号为"' + chapterIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delChapter(chapterIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有培训章节管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportChapter(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    }
  }
};
</script>